package com.hnluchuan.bmjlearning.web.controller.admin;

import com.hnluchuan.bmjlearning.common.ExcelUtils;
import com.hnluchuan.bmjlearning.dto.AgentDTO;
import com.hnluchuan.bmjlearning.dto.CustomerDTO;
import com.hnluchuan.bmjlearning.model.Customer;
import com.hnluchuan.bmjlearning.web.controller.BaseController;
import com.hnluchuan.utils.exception.BizException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
@RequestMapping(value = "admin/reportForm" , produces="text/html;charset=UTF-8")
public class AdminReportFormController extends BaseController{
    @ResponseBody
    @RequestMapping(value = "/exportCustomer", produces="text/html;charset=UTF-8")
    public void exportCustomer(HttpServletRequest request, HttpServletResponse response, Integer status, Long agentId) throws Exception {
        CustomerDTO query = new CustomerDTO();
        query.setAgentId(agentId);
        query.setStatus(status);
        List<CustomerDTO> customers = customerService.findAll(query);
        if (ArrayUtils.isEmpty(customers.toArray())) {
            throw new BizException("当前没有可导出的医生信息");
        }
        //excel标题机构名称	客户名称	联系方式
        String[] title = {"机构名称", "医生名称", "联系方式"};
        //excel文件名
        String fileName = "医生信息表" + System.currentTimeMillis() + ".xls";
        //sheet名
        String sheetName = "医生信息表";
        String[][] content = new String[customers.size()][title.length];
        for (int i = 0; i < customers.size(); i++) {
            CustomerDTO c = customers.get(i);
            content[i] = new String[title.length];
            content[i][0] = c.getOrgName();
            content[i][1] = c.getName();
            content[i][2] = c.getMobile();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载医生信息导入模板
     *
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public String download(HttpServletResponse response) throws Exception {
        String path = this.getClass().getClassLoader().getResource("").getPath();
        path += "doctorInfo.xlsx";
        logger.debug(String.format("path : %s", path));
        InputStream in = new FileInputStream(path);
        String fileName = "医生信息导入模板.xlsx";
        fileName = new String(fileName.getBytes("utf-8"), "ISO8859-1");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        int length;
        while ((length = in.read(b)) > 0) {
            os.write(b, 0, length);
        }
        in.close();
        return null;
    }

    /**
     * 代理商导入新用户
     * */
    @ResponseBody
    @Transactional
    @RequestMapping(value = "/importCustomer", method = RequestMethod.POST, produces="text/html;charset=UTF-8")
    public String infoImport(HttpServletRequest request) throws Exception {
        Long agentId = getCurrentAgentDTO().getId();
        // 多部请求解析器
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 是否为多部请求
        if (resolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("file");
            if (file != null) {
                InputStream inputStream = file.getInputStream();
                //读取Excel表格中的数据
                List<Customer> customers =
                        customerService.readCustomerByInputStream(inputStream);
                //存在的账号
                List<String> customerMobiles = customerService.failedCustomerMobile(customers);
                int successNumber = customerService.creatCustomer(customers, agentId);

                //更新代理商下的医生数量
                AgentDTO dto = agentService.load(agentId);
                Integer customerNums = dto.getCustomers();
                customerNums += successNumber;
                dto.setCustomers(customerNums);
                agentService.updateAllFields(dto);
                //格式异常的账号
                int size = customers.size();
                if (successNumber < size) {
                    String index = String.format("总计%d条医生信息，成功导入%d条，失败%d条。<br>", size, successNumber, size - successNumber);
                    StringBuilder sb = new StringBuilder(index);
                    for (String customerMobile : customerMobiles) {
                        sb.append("账号["+customerMobile+"]导入失败<br>");
                    }
                    return ok(sb.toString());
                }
            }
        }
        return ok();
    }



    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
